package com.ylw.entity.request;

import com.ylw.entity.Request;
import com.ylw.inter.GenerateStatement;
import com.ylw.util.Constant;

import java.util.ArrayList;
import java.util.List;

public class EsbHttpService implements GenerateStatement {


    @Override
    public String generatClass(String className) {
        StringBuilder sb = new StringBuilder();
        sb.append("package com.ct10000.esb.service.impl;"+Constant.LINESEPARATOR);
        sb.append(Constant.LINESEPARATOR);
        sb.append("import com.ct10000.esb.cfg.domain.Wt_esb_service_defDomain;"+Constant.LINESEPARATOR);
        sb.append("import com.ct10000.esb.cfg.domain.Wt_esb_service_instanceDomain;"+Constant.LINESEPARATOR);
        sb.append("import com.ct10000.esb.context.ActionContext;"+Constant.LINESEPARATOR);
        sb.append("import com.ct10000.esb.service.Service;"+Constant.LINESEPARATOR);
        sb.append("import net.sf.json.JSONObject;"+Constant.LINESEPARATOR);
        sb.append("import org.apache.commons.httpclient.HttpClient;"+Constant.LINESEPARATOR);
        sb.append("import org.apache.commons.httpclient.HttpException;"+Constant.LINESEPARATOR);
        sb.append("import org.apache.commons.httpclient.HttpStatus;"+Constant.LINESEPARATOR);
        sb.append("import org.apache.commons.httpclient.methods.PostMethod;"+Constant.LINESEPARATOR);
        sb.append("import org.apache.commons.httpclient.methods.StringRequestEntity;"+Constant.LINESEPARATOR);
        sb.append("import org.apache.commons.httpclient.params.HttpMethodParams;"+Constant.LINESEPARATOR);
        sb.append("import java.io.IOException;"+Constant.LINESEPARATOR);
        sb.append("import java.io.UnsupportedEncodingException;"+Constant.LINESEPARATOR);
        sb.append("import java.text.SimpleDateFormat;"+Constant.LINESEPARATOR);
        sb.append("import java.util.Date;"+Constant.LINESEPARATOR);
        sb.append("import java.util.HashMap;"+Constant.LINESEPARATOR);
        sb.append("import java.util.Map;"+Constant.LINESEPARATOR);
        sb.append("import java.util.UUID;"+Constant.LINESEPARATOR);
        sb.append(Constant.LINESEPARATOR);
        sb.append("public class "+className+"Service implements Service {"+Constant.LINESEPARATOR);
        return sb.toString();
    }

    @Override
    public String generateMethod(String methodName, Request request) {
        StringBuilder sb = new StringBuilder();
        sb.append("Map returnMap = new HashMap();");
        sb.append(Constant.LINESEPARATOR);
        sb.append("returnMap.put(\"resultCode\",\"-1\");");
        sb.append(Constant.LINESEPARATOR);
        sb.append("returnMap.put(\"msg\",\"\");");
        sb.append(Constant.LINESEPARATOR);
        sb.append("JSONObject req = new JSONObject()");
        sb.append(Constant.LINESEPARATOR);
        sb.append("JSONObject biz = new JSONObject()");
        sb.append(Constant.LINESEPARATOR);
        sb.append("JSONObject head = null;");
        sb.append(Constant.LINESEPARATOR);
        sb.append("Map postResult = null;");
        sb.append(Constant.LINESEPARATOR);
        sb.append(appendInputPara2JSON("biz",request));

        sb.append("/**"+Constant.LINESEPARATOR);
        sb.append("*参数校验"+Constant.LINESEPARATOR);
        sb.append("*/"+Constant.LINESEPARATOR);

        sb.append("/**"+Constant.LINESEPARATOR);
        sb.append("*生成请求头模块"+Constant.LINESEPARATOR);
        sb.append("*/"+Constant.LINESEPARATOR);

        sb.append("json.put(\"head\", head);"+Constant.LINESEPARATOR);
        sb.append("json.put(\"biz\", biz);"+Constant.LINESEPARATOR);
        sb.append("postResult = postClient(paramStr, postURL);"+Constant.LINESEPARATOR);

        sb.append("//处理post请求"+Constant.LINESEPARATOR);
        sb.append("String resultCode = (String) postResult.get(\"resultCode\");"+Constant.LINESEPARATOR);
        sb.append("String resultStr = (String) postResult.get(\"resultStr\");"+Constant.LINESEPARATOR);
        sb.append("if (!\"success\".equals(resultCode)) {"+Constant.LINESEPARATOR);
        sb.append("    resultMap = JSONObject.fromString(resultStr);"+Constant.LINESEPARATOR);
        sb.append("    returnMap.put(\"resultCode\", \"-1\");"+Constant.LINESEPARATOR);
        sb.append("    returnMap.put(\"resultMsg\", \"postErr\");"+Constant.LINESEPARATOR);
        sb.append("    return returnMap;"+Constant.LINESEPARATOR);
        sb.append("}"+Constant.LINESEPARATOR);

        sb.append("//对返回的结果进行处理"+Constant.LINESEPARATOR);
        sb.append("//对返回的结果进行处理"+Constant.LINESEPARATOR);
        sb.append("//对返回的结果进行处理"+Constant.LINESEPARATOR);

        sb.append("catch (Exception e) {"+Constant.LINESEPARATOR);
        sb.append("    e.printStackTrace();"+Constant.LINESEPARATOR);
        sb.append("    LOG.error(e.getMessage());"+Constant.LINESEPARATOR);
        sb.append("    resultMap.put(\"resultMsg\", e.getMessage());"+Constant.LINESEPARATOR);
        sb.append("}"+Constant.LINESEPARATOR);


        sb.append("//返回值处理"+Constant.LINESEPARATOR);
        sb.append(" returnMap.put(\"resultCode\", code);"+Constant.LINESEPARATOR);
        sb.append(" returnMap.put(\"resultFlag\", resultFlag);"+Constant.LINESEPARATOR);

        sb.append("return returnMap;"+Constant.LINESEPARATOR);
        sb.append("}"+Constant.LINESEPARATOR);


        return sb.toString();
    }

    /**
     * 对 request处理  因为request里面的map结构不确定
     * 这里先处理了 当没有head和body这些map时 此时整个request.map每个key对应的list大小只有一个
     * {"map":{productNBR=[{"allowNull":false,"order":2}{"name":"productNBR","type":"String","remark":"主套餐NBR编码、宽带甩单NBR编码"}], idcardno=[{"allowNull":false,"order":8}{"name":"idcardno","type":"String","remark":"身份证号码、宽带续约身份证号码"}], provinceCode=[{"allowNull":true,"order":4}{"name":"provinceCode","type":"String","remark":"省编码参见附录【2】组织机构编码"}], cityCode=[{"allowNull":true,"order":5}{"name":"cityCode","type":"String","remark":"市编码参见附录【2】组织机构编码"}], sendCusmobile=[{"allowNull":false,"order":10}{"name":"sendCusmobile","type":"String","remark":"收货人号码"}], number=[{"allowNull":false,"order":6}{"name":"number","type":"String","remark":"入网手机号"}], custName=[{"allowNull":false,"order":7}{"name":"custName","type":"String","remark":"姓名"}], sendCusname=[{"allowNull":false,"order":9}{"name":"sendCusname","type":"String","remark":"收货人姓名"}], productName=[{"allowNull":false,"order":3}{"name":"productName","type":"String","remark":"主套餐NBR名称、宽带甩单NBR名称"}], orderId=[{"allowNull":true,"order":1}{"name":"orderId","type":"String","remark":"集团电渠订单编号，例如：609001811001008320180306917541"}]},"table":org.apache.poi.xwpf.usermodel.XWPFTable@9921360,"service":com.ylw.entity.Service@55360888,"header":0}
     *
     * @param jsonName
     * @param request
     * @return
     */
    private String appendInputPara2JSON(String jsonName, Request request) {
        List parameters = new ArrayList();
        StringBuilder sb = new StringBuilder();
        //因为这个request没有head等直接处理
        for(Object o: request.getMap().keySet()){
            parameters.addAll(request.getMap().get(o.toString()));
//            可以对请求头处理
//            if("head".equalsIgnoreCase(o.toString())){
//                appendInputPara2JSON("head",parameters);
//            }
            sb.append(appendInputPara2JSON(jsonName,parameters));
        }



        return sb.toString();
    }

    /**
     * 通过每个request列表 生成java代码
     * @param jsonName
     * @param parameters
     * @return
     */
    private String appendInputPara2JSON(String jsonName, List<RequestParameter> parameters) {
        StringBuilder sb = new StringBuilder();
        for (RequestParameter p : parameters) {
            sb.append("if (actionContext.getAttribute(\"" + p.getName() + "\") !=null");
            if (p.getType().equalsIgnoreCase("string")) {
                sb.append("|| \"\".equals(actionContext.getAttribute(\"" + p.getName() + "\"))");
            }
            sb.append("){" + System.getProperty("line.separator"));
            sb.append(jsonName + ".put(\"" + p.getName() + "\", (" + p.getType() + ") actionContext.getAttribute(\"" + p.getName() + "\"));" + System.getProperty("line.separator"));
            sb.append("}" + System.getProperty("line.separator"));
            if (!p.getAllowNull()) {
                sb.append("else{"+Constant.LINESEPARATOR);
                sb.append("returnMap.put(\"msg\", \""+p.getName()+"不能为空\");"+Constant.LINESEPARATOR);
                sb.append("return returnMap;"+Constant.LINESEPARATOR);
            }
        }
        return sb.toString();
    }

}
